package forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author lyx
 * @Date 2021/6/26 13:43
 * forkjoin计算0~10亿的和
 * 优点:可以调节临界值,临界值越大,拆分越多,耗费时间越少
 * 缺点:效率低,推荐使用stream流
 */
public class ForkJoinTest  extends RecursiveTask<Long>{//泛型=返回值类型
    private Long start;   //0
    private Long end;    //10_0000_0000L
    private Long temp = 10000000L; //临界值

    //new之后走构造,提示传start 和 end 进来
    public ForkJoinTest(Long start, Long end) {
        this.start = start;
        this.end = end;
    }
    //重写计算方法
    @Override
    protected Long compute() {

        if ((end-start)<temp) {//如果不超过中间变量
            Long sum = 0L;//总和
            System.out.println("不是f");
            for (Long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        } else {//超过中间变量,用forkjoin递归计算
            System.out.println("走的是forkjoin");
            Long middle = (start+end)/2; //中间值
            ForkJoinTest task1 = new ForkJoinTest(start,middle);
            task1.fork();  //把拆分的task1压入栈
            ForkJoinTest task2 = new ForkJoinTest(middle,end);
            task2.fork();
            return (Long) task1.join()+(Long)task2.join();
        }
    }
}
